package tcp.通过tcp实现通信;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class TheServiceSide {
    public static void main(String[] args) {
        //1.给一个地址
        ServerSocket socket = null;
        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream stream = null;
        try {
            //1.需要一个地址
            socket = new ServerSocket(9999);//调用构造方法，给一个端口号
            //2.接收消息
            accept = socket.accept();//侦听类
            inputStream = accept.getInputStream();//输入字节流

            //管道流
            stream = new ByteArrayOutputStream();//管道输出流
            byte[] zj = new byte[1024];
            int len;
            while ((len = inputStream.read(zj)) != -1) {
                stream.write(zj, 0, len);
            }

            System.out.println(stream.toString());


//            inputStream.read(zj,0,1024);
//            System.out.println(zj[0]);
//            int len ;
//            while ((len=inputStream.read(zj))!=-1){
//                String s = new String(zj,0,len);
//                System.out.println(s);
//            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
